package com.zhaotianhao.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.zhaotianhao.pojo.Order;
import com.zhaotianhao.pojo.Users;
import com.zhaotianhao.service.OrderService;
import com.zhaotianhao.util.AlibabapayGateWayUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.ProducerListener;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author Z-7
 * @Date 2022/3/3
 */
@Controller
@RequestMapping("order")
public class OrderController {
    @DubboReference
    private OrderService orderService;
    @Resource
    private KafkaTemplate kafkaTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @PostConstruct
    public void initKafka(){
        kafkaTemplate.setProducerListener(new ProducerListener<String,String>(){
            public void onSuccess(String topic, Integer partition, String key, String value, RecordMetadata recordMetadata) {
                System.out.println("kafka发送消息成功:topic:" + topic + "key:" + key + "value:" + value);
            }
            public void onError(String topic, Integer partition, String key, String value, Exception exception) {
                System.err.println("kafka发送消息失败:topic:" + topic + "key:" + key + "value:" + value);
            }
        });
    }
    @RequestMapping("creatOrder")
    public String creatOrder(Integer ids[], HttpSession session, Model model){
        Users login_user = (Users) session.getAttribute("LOGIN_USER");
        if(login_user == null){
            return "redirect:../user/login";
        }
        Order order = orderService.createOrder(ids,login_user.getId());
        if(order != null){
            model.addAttribute("order",order);
            return "orders/order_list";
        }
        return "carts/carts_list";
    }

    /**
     * 去支付
     * @param id
     * @param session
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping(value = "pay",produces = "text/html;charset =utf-8")
    public @ResponseBody String pay(String id, HttpSession session) throws AlipayApiException {
        Users login_user = (Users) session.getAttribute("LOGIN_USER");
        Order order = orderService.queryById(id,login_user.getId());
        String payUrl = AlibabapayGateWayUtils.createOrder(id, order.getFactPrice().toString(), "购买商品", "商品满减");
        return payUrl;
    }

    /**
     * 支付成功
     * @param request
     * @param out_trade_no
     * @param total_amount
     * @return
     */
    @RequestMapping("callBack")
    public String callBack(HttpServletRequest request, String out_trade_no, String total_amount){
        Users login_user = (Users) request.getSession().getAttribute("LOGIN_USER");
        // 获取订单的信息
        Order order = orderService.queryById(out_trade_no, login_user.getId());
        // 防止消息丢失 (存入redis中)
        //redisTemplate.opsForHash().put("order",out_trade_no,order);
        // kafka 发送消息
        kafkaTemplate.send("1909a","order", JSON.toJSONString(order));
        // 修改订单的状态
        //orderService.updateOrderStatus(order.getId(),1);// 修改为已经支付的状态
        request.setAttribute("order",order);
        return "users/callBack";// 支付完成的页面
    }
}
